package com.yixun.qfbao.util;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.constant.WxConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 
 * @author zilong.liu
 *	封装一些微信的常用请求方法
 */
@Slf4j
@Component
public class WxReqestUtil {
	
	@Autowired
	WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

	private static final int RETRY_TIMES = 3;
	
	public String getUnionId(String openId, String companyUuid, String loginType, int retryTimes) {
		if(retryTimes >= RETRY_TIMES) {
			return null;
		}
		String token = wxAccessTokenCacheUtils.getAccessTokenBySystemId(companyUuid, loginType, "");
		if(token == null || StringUtils.isEmpty(token)) {
			return null;
		}
		String unionId = getUnionId(token, openId);
		if("40001".equals(unionId)) {
			wxAccessTokenCacheUtils.remove(companyUuid, loginType);
			return getUnionId(openId, companyUuid, loginType, retryTimes++);
		}
		return unionId;
	}
	
	private String getUnionId(String token, String openId) {
		String url = WxConstant.GET_USER_INFO;
    	url = url.replace("ACCESS_TOKEN", token);
    	url = url.replace("OPENID", openId);
    	log.info("msgSubscriptionService->getUnionId->url:{}", url);
    	PorxyResult porxyResult = PorxyUtil.getPorxy(url);
    	if(!"0".equals(porxyResult.getStatus().getNo())) {
    		log.error("msgSubscriptionService->getUnionId->请求失败:", porxyResult.getContext());
    		return "";
    	}
    	String context = porxyResult.getContext();
    	log.info("WxReqestUtil->getUnionId->->context:{}", context);
    	JSONObject contextJson = JSONObject.parseObject(context);
    	Object unionIdObj = contextJson.get("unionid");
    	if(unionIdObj == null) {
    		return contextJson.getString("errcode");
    	}
    	return unionIdObj.toString();
	}
}
